package com.ihai.spring.boot.sample.distributed.counter.model;


import com.ihai.spring.boot.sample.distributed.counter.handler.CallMasterInvoker;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.Serializable;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.List;

/**
 * DESC
 *
 * @author 张驰
 * @date 2019/12/23
 */
public class CounterProxy implements InvocationHandler {
    private static final Logger logger = LoggerFactory.getLogger(CounterProxy.class);
    private static List<String> OPT_METHODS = new ArrayList<>();

    static {
        OPT_METHODS.add("setValue");
        OPT_METHODS.add("reset");
        OPT_METHODS.add("incr");
        OPT_METHODS.add("add");
        OPT_METHODS.add("setAvailableTime");
        OPT_METHODS.add("setTimeout");
        OPT_METHODS.add("isAvailable");
    }

    private ICounter counter;

    public ICounter getInstance(ICounter counter) {
        this.counter = counter;
        return (ICounter) Proxy.newProxyInstance(counter.getClass().getClassLoader(), counter.getClass().getInterfaces(), this);
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        if (!counter.isMaster() && OPT_METHODS.contains(method.getName())) {
            return CallMasterInvoker.invoke((ICounter) proxy, method, args);
        } else {
            return method.invoke(counter, args);
        }

    }
}
